package net.easyjava.tools.cookie;

import net.easyjava.tools.BaseTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by wenxiaoning on 15/12/21.
 */
public class CookieTools extends BaseTools{
    private static Logger logger = LoggerFactory.getLogger(CookieTools.class);

    /**
     * 设置cookie
     * @param response
     * @param key
     * @param value
     * @param maxAge
     * @param path
     */
    public static void setCookie(HttpServletResponse response,String key,String value,int maxAge,String domain,String path,boolean isHttpOnly){
//        Cookie cookie = new Cookie(key,value);
//        cookie.setPath(path);
//        cookie.setDomain(domain);
////        cookie.setHttpOnly(isHttpOnly);
//        if(maxAge>0)  cookie.setMaxAge(maxAge);
//        response.addCookie(cookie);

        saveCookie(response,key,value,maxAge,domain,path,isHttpOnly);

    }

    /**
     * 设置cookie
     */
    private static void saveCookie(HttpServletResponse response, String name,
                                  String value, int maxAge, String domain,String path, boolean httponly) {
        StringBuilder cookie = new StringBuilder(name);
        cookie.append("=");
        cookie.append(value);
        cookie.append("; path=");
        cookie.append(path);
        cookie.append("; ");
        cookie.append("domain=");
        cookie.append(domain);

        if (maxAge != -1) {
            Date date = new Date();
            long time = 1000l * maxAge + date.getTime();
            String toGMTString = toGMT(time);
            cookie.append("; expires=");
            cookie.append(toGMTString);
        }
        if (httponly)
            cookie.append("; HttpOnly");

        response.addHeader("Set-Cookie", cookie.toString());
    }

    public static void setCookieHttpOnly(HttpServletResponse response,String key,String value,int maxAge,String domain){
        setCookie(response, key, value, maxAge, domain, "/", true);
    }
    public static void setCookie(HttpServletResponse response,String key,String value,int maxAge,String domain){
        setCookie(response, key, value, maxAge, domain, "/", false);
    }
    public static void setCookie(HttpServletResponse response,String key,String value,String domain){
        setCookie(response, key, value, 0, domain);
    }

    /**
     * 根据名字获取cookie
     * @param request
     * @param name cookie名字
     * @return
     */
    public static Cookie getCookie(HttpServletRequest request,String name){
        Map<String,Cookie> cookieMap = getCookies(request);
        if(cookieMap.containsKey(name)){
            Cookie cookie = (Cookie)cookieMap.get(name);
            return cookie;
        }else{
            return null;
        }
    }



    /**
     * 将cookie封装到Map里面
     * @param request
     * @return
     */
    public static Map<String,Cookie> getCookies(HttpServletRequest request){
        Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
        Cookie[] cookies = request.getCookies();
        if(null!=cookies){
            for(Cookie cookie : cookies){
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }

    /**
     * 删除cookie
     * @param request
     * @param name
     */
    public static void removeCookie(HttpServletRequest request,HttpServletResponse response,String name){

        Cookie cookie = getCookie(request, name);
        if(cookie == null){
            logger.error(name+".cookie is null");
            throw new NullPointerException(name+".cookie is null");
        }


        cookie.setMaxAge(0);
        cookie.setValue(null);
        response.addCookie(cookie);
    }


    private static String toGMT(long time) {
        Calendar cd = Calendar.getInstance();
        cd.setTimeInMillis(time);
        SimpleDateFormat sdf = new SimpleDateFormat(
                "EEE, d-MMM-yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        String timeStr = sdf.format(cd.getTime());
        return timeStr;
    }
}
